<template>
  <div class="page">
    <van-nav-bar title="发布种草" left-arrow @click-left="handleBack" />
    <van-uploader 
      v-model="images" 
      :max-count="3" 
      preview-size="80px" 
      preview-teleport="body"
      :after-read="handleImageRead"
    >
      <template #preview-item="props">
        <img :src="props.item" class="preview-image" />
      </template>
    </van-uploader>

    <van-field v-model="title" placeholder="输入标题" type="text" class="input-margin" />
    <van-field v-model="content" placeholder="输入种草内容" type="textarea" autosize class="input-margin" />

    <van-cell-group>
      <van-cell title="关联商品">
        <select v-model="selectedGoods" class="select-input">
          <option value="" disabled>请选择商品</option>
          <option v-for="(goods, index) in lianjie_lst" :key="index" :value="goods.id">{{ goods.l_name }}</option>
        </select>
        <van-icon name="close" size="20px" color="#ff4444" @click="clearSelectedGoods" class="delete-icon" />
      </van-cell>
    </van-cell-group>

    <van-cell-group>
      <van-cell title="选择参与话题">
        <select v-model="selectedTopic" class="select-input">
          <option value="" disabled>请选择话题</option>
          <option v-for="(topic, index) in tag_lst" :key="index" :value="topic.id">#{{ topic.t_name }}</option>
        </select>
        <van-icon name="close" size="20px" color="#ff4444" @click="clearSelectedTopic" class="delete-icon" />
      </van-cell>
    </van-cell-group>

    <van-button type="primary" block class="publish-btn" @click="handlePublish">发布</van-button>
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import http from '../../http/index';

const router = useRouter();
const images = ref([]);
const title = ref('');
const content = ref('');
const selectedGoods = ref(null);
const selectedTopic = ref(null);
const errorMessage = ref('');


// 获取商品列表
const lianjie_lst = ref([]);
const get_lianjie = () => {
  http.get('/home/lianjie/')
    .then(res => {
      lianjie_lst.value = res.data;
    })
    .catch(error => {
      console.error('获取商品列表失败:', error);
    });
};

// 获取话题列表
const tag_lst = ref([]);
const get_tag = () => {
  http.get('/home/tag/')
    .then(res => {
      tag_lst.value = res.data;
    })
    .catch(error => {
      console.error('获取话题列表失败:', error);
    });
};

// 清除商品选择
const clearSelectedGoods = () => {
  selectedGoods.value = null;
};

// 清除话题选择
const clearSelectedTopic = () => {
  selectedTopic.value = null;
};

// 处理图片上传后的回调（可选）
const handleImageRead = (file) => {
  // 如需额外处理图片，可在此添加逻辑
};

// 假设这是从会话中获取的用户 ID
const userId = ref(localStorage.getItem('user_id'));

// 表单验证
const validateForm = () => {
  if (!title.value) {
    errorMessage.value = '标题不能为空';
    return false;
  }
  if (!content.value) {
    errorMessage.value = '内容不能为空';
    return false;
  }
  if (!selectedTopic.value) {
    errorMessage.value = '请选择参与话题';
    return false;
  }
  errorMessage.value = '';
  return true;
};


// 发布处理
const handlePublish = async () => {
  if (!validateForm()) {
    return;
  }
  try {
    const formData = new FormData();
    formData.append('t_user', userId.value);
    formData.append('likes_count', 0);

    // 直接上传 File 对象
    images.value.forEach((file) => {
      formData.append('t_img', file.file);
    });

    formData.append('t_title', title.value);
    formData.append('t_content', content.value);
    formData.append('lianjie', selectedGoods.value);
    formData.append('fen_tag', selectedTopic.value);

    const token = localStorage.getItem('token');
    console.log('Token:', token); // 调试输出

    const response = await http.post('/home/new-create-tiezi/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token.trim()}` // 去除可能的空格
      }
    });
    console.log('发布成功:', response.data);

    // 尝试添加更多调试信息
    console.log('准备跳转至 /UserCenter');
    router.push({ path: '/UserCenter' }).then(() => {
      console.log('跳转成功');
      console.log('测试跳转首页');
      
      location.reload(); // 刷新页面
    }).catch((error) => {
      console.error('跳转失败:', error);
    });
  } catch (error) {
    if (error.response) {
      errorMessage.value = error.response.data.error || '发布失败，请稍后重试';
    } else {
      errorMessage.value = '发布失败，请检查网络连接';
    }
    console.error('发布失败:', error);
  }
};

// // 发布处理
// const handlePublish = async () => {
//   if (!validateForm()) {
//     return;
//   }
//   try {
//     const formData = new FormData();
//     formData.append('t_user', userId.value);
//     formData.append('likes_count', 0);

//     // 直接上传 File 对象
//     images.value.forEach((file) => {
//       formData.append('t_img', file.file);
//     });

//     formData.append('t_title', title.value);
//     formData.append('t_content', content.value);
//     formData.append('lianjie', selectedGoods.value);
//     formData.append('fen_tag', selectedTopic.value);

//     const token = localStorage.getItem('token');
//     console.log('Token:', token); // 调试输出

//     const response = await http.post('/home/new-create-tiezi/', formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data',
//         // 'Authorization': `Bearer ${localStorage.getItem('token')}`
//         'Authorization': `Bearer ${token.trim()}` // 去除可能的空格
//       }
//     });
//     router.push({ path: '/UserCenter' })
//     console.log('发布成功:', response.data);
    
    
   
    // router.push("/UserCenter");
    
//   } catch (error) {
//     if (error.response) {
//       errorMessage.value = error.response.data.error || '发布失败，请稍后重试';
//     } else {
//       errorMessage.value = '发布失败，请检查网络连接';
//     }
//     console.error('发布失败:', error);
//   }
// };

onMounted(() => {
  get_tag();
  get_lianjie();
});

const handleBack = () => {
  router.back();
};
</script>

<style scoped>
.page {
  padding: 16px;
  background-color: #fff;
}

.input-margin {
  margin: 16px 0;
}

.publish-btn {
  margin-top: 32px;
  background-color: #ff8198;
  border-color: #ff8198;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.select-input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: calc(100% - 40px); /* 为图标留空间 */
  margin-right: 10px;
  vertical-align: middle;
}

.delete-icon {
  vertical-align: middle;
}

.error-message {
  color: red;
  margin-top: 10px;
}
</style>